package br.com.fiap.mercadinho.bean;

import java.io.Serializable;

import br.com.fiap.mercadinho.common.DAOException;
import br.com.fiap.mercadinho.dao.ProductDAO;
import br.com.fiap.mercadinho.dao.StockDAO;

public class Product implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3528786657163207555L;
	private Integer id;
	private Double price;
	private String description;
	private Integer quantity;
	
	

	public Integer getQuantity() {
		return quantity;
	}

	public void setQuantity(Integer quantity) {
		this.quantity = quantity;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public void setId(String id) {
		if (id != null && !id.equals("")) {
			this.id = Integer.valueOf(id);
		} else {
			this.id = 0;
		}
	}

	public Double getPrice() {
		return price;
	}

	public void setPrice(Double price) {
		this.price = price;
	}

	public void setPrice(String price) {
		try {
			
			this.price = Double.parseDouble(price.replace(',','.'));
		} catch (Exception e) {
			// if price is not number valid set null
			price = null;
		}
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}
	
	public String validateProduct(){
		
		if (this.description == null || this.description.equals(""))
			return "Campo descri�ao e obrigatorio.";
		if (this.price == null)
			return "Campo preco deve estar no formato 99.99";
		
		return "";
	}
	
	public void saveProductAndRegisterInStock() throws DAOException{
		ProductDAO daoProductDAO = new ProductDAO();
		StockDAO stockDAO = new StockDAO();
		daoProductDAO.saveProduct(this);
		//register product in stock
		this.setId(daoProductDAO.getLastInsertId());
		stockDAO.saveStockProduct(new Stock(this));
	}

	
	public Double getTotalPrice(){
		return price * quantity;
	}
}
